<?php

namespace App\CommandModel;

use App\Helpers\Helpers;
use App\Model\Order;
use App\Model\WeChatNotify;
use Illuminate\Support\Facades\DB;

class OrderExpire
{
    public function run()
    {
        //更改超时未领取的订单为过期
        DB::table('orders')->where('expire_time','<',date('Y-m-d H:i:s'))->where('state','=',3)
            ->whereNull('deleted_at')
            ->update(['state'=>4]);

        //查找已支付过期订单，并发起退款
        $model = (new Order())->where('state','=',4)
            ->where('is_pay','yes');

        $model->chunk(10,function ($items){
            $err = [];
            foreach ($items as $item){
                if($pay = $item->payRecord){
                    $bool = $pay->refund("过期退款");
                    if ($bool) {
                        $item->state = 9;
                        $item->save();
                    }else{
                        $err[] = [$item->out_trade_no=>$pay->errMsg];
                    }
                }
            }
            Helpers::log('[refund error]'.json_encode($err),'payment');
        });

        $this->expireNotify();

        return false;
    }

    public function expireNotify()
    {
        $t = \config('order.order_expire_notify_time');
        //查找快过期订单，并发消息
        $model = (new Order())->where('state','=',3)
            ->where('expire_time','<=',date('Y-m-d H:i:s',time()+$t))
            ->whereNull('last_expire_notify_time');

        $model->chunk(10,function ($items){
            $err = [];
            foreach ($items as $item){
                $m = new WeChatNotify();
                $bool = $m->cardExpire($item);

                if ($bool) {
                    $item->last_expire_notify_time = date('Y-m-d H:i:s');
                    $item->save();
                }
                $err[] = [$item->out_trade_no=>$bool];
            }
            Helpers::log('[refund error]'.json_encode($err),'order_expire');
        });
        return false;
    }

}
